package JSF;

import Entidades.MovExp;
import Entidades.Trabajador;
import Entidades.Usuario;
import JSF.util.JsfUtil;
import JSF.util.PaginationHelper;
import SessionB.UsuarioFacade;
import java.io.BufferedInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import java.io.Serializable;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;

@Named("usuarioController")
@SessionScoped
public class UsuarioController implements Serializable {

    private MovExp movexp;
    private Usuario current;
    private DataModel items = null;
    @EJB
    private SessionB.UsuarioFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private int tipUserl;
    private Usuario usuario;
    private Trabajador trabajador;
    private List<Usuario> lista;
    private List<Usuario> list_usuario;
    private List<Usuario> filteredUsuario;

    public UsuarioController() {
        usuario = new Usuario();
        lista = new LinkedList<Usuario>();
        list_usuario = new ArrayList<Usuario>();
    }

    public Usuario getSelected() {
        if (current == null) {
            current = new Usuario();
            selectedItemIndex = -1;
        }
        return current;
    }

    private UsuarioFacade getFacade() {
        return ejbFacade;
    }

    public MovExp getMovexp() {
        return movexp;
    }

    public void setMovexp(MovExp movexp) {
        this.movexp = movexp;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public int getTipUserl() {
        return tipUserl;
    }

    public void setTipUserl(int tipUserl) {
        this.tipUserl = tipUserl;
    }

    public Trabajador getTrabajador() {
        return trabajador;
    }

    public void setTrabajador(Trabajador trabajador) {
        this.trabajador = trabajador;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Usuario) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Usuario();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UsuarioCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Usuario) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UsuarioUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Usuario) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    public List<Usuario> getListaUsuarioAll() {
        lista = new LinkedList<Usuario>();
        try {
            lista = ejbFacade.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lista;
    }

    public String eliminaUsuario() {
        try {
//             almProductoFacade.remove(producto);
            System.out.println(" ----------- Usuario Eliminado ");
            ejbFacade.remove(usuario);

        } catch (Exception e) {
            e.printStackTrace();
        }

        //  return "requerimientos";
        return null;
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("UsuarioDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Usuario getUsuario(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    /**
     * @return the usuario
     */
    public Usuario getUsuario() {
        return usuario;
    }

    /**
     * @param usuario the usuario to set
     */
    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public String logIny() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
        EntityManager em = factory.createEntityManager();
        Query q = em.createQuery("SELECT u FROM Usuario u WHERE u.usuario = :USER_NAME and u.clave = :USER_PASS ");
        q.setParameter("USER_NAME", usuario.getUsuario());
        q.setParameter("USER_PASS", usuario.getClave());
        //MdcoreProject mi_proyecto_buscado = (MdcoreProject) 
        Usuario usuario2;
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;
        String page = null;

        //   loggedIn = true;
        //   msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
        usuario2 = (Usuario) q.getSingleResult();
        this.usuario = usuario2;
//            System.out.println(" ---------- Tipo de usuario : " + usuario2.getTipoUsuario().getIdTipoUsuario());
        int tuser = usuario2.getTipoUsuario().getIdTipoUsuario();
        if (tuser > 0) {
            String nauser = usuario2.getUsuario();
//            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Acceso al Sistema ", "Bienvenido al Sistema "+nauser);
//            RequestContext.getCurrentInstance().showMessageInDialog(message);

            //      FacesContext context = FacesContext.getCurrentInstance();
            //      context.addMessage(null, new FacesMessage("Bienvenido al Sistema " + nauser, "._."));
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", nauser);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            if (tuser == 3) {
                page = "indexuser?faces-redirect=true";
            } else {
                page = "index?faces-redirect=true";
            }
            //     return page;
        } else {
            System.out.println(" --- Error en Login ");
//            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Acceso al Sistema ", "Error, Verificar Usuario y Password ?");
//            RequestContext.getCurrentInstance().showMessageInDialog(message);
            //      FacesContext context = FacesContext.getCurrentInstance();
            //      context.addMessage(null, new FacesMessage("Error, Verificar Usuario y Password ?", ":_:"));
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
            FacesContext.getCurrentInstance().addMessage(null, msg);

            page = "logon?faces-redirect=true";
            usuario2 = null;

        }
        return page;
    }

    public boolean condicion() {
        if (tipUserl == 1 || tipUserl == 2) {
            return true;
        } else if (tipUserl == 3) {
            return true;
        } else {
            return false;
        }
    }

    public boolean condicion1() {
        if (tipUserl == 1) {
            return false;
        } else {
            return true;
        }
    }

    public boolean condicion2() {
        if (tipUserl == 2 || tipUserl == 1) {
            return false;
        } else {
            return true;
        }
    }

    public boolean condicion3() {
        if (tipUserl == 3) {
            return false;
        } else {
            return true;
        }
    }

    public boolean mio() {
        String usermio = seekUser();
        String usergrabo = movexp.getTrabajador().getIdResponsable();
        System.out.println(" modificar userMio : " + usermio);
        System.out.println(" modificar userGrab: " + usergrabo);
        if (usermio.equals(usergrabo)) {
            return true;
        } else {
            return false;
        }
    }

    public boolean loggedIn() {
        //    User user = (User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
//        System.out.println("  -- Usuario : "+usuario.getUsuario());
        //      System.out.println("  -- Password: "+usuario.getClave());

        /*     HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
         System.out.println(" req : "+req);
         HttpServletResponse resp = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
         System.out.println(" resp : "+resp);
         HttpSession session = req.getSession(true); 
         System.out.println(" session : "+session);
         System.out.println(" get id : "+session.getId());
         String pageRequested = req.getRequestURL().toString();
         System.out.println(" pageRequested : "+pageRequested);
         String page = null;
         System.out.println(" ............. Session : "+session.getAttribute(pageRequested));
         */
//        if (session.getAttribute(pageRequested)==null) {
        String logeado = usuario.getUsuario().trim();
        System.out.println(" antes del If de logue=null : " + logeado);
// antes        if (logeado.equals(null)) {            
        if (logeado == null) {
            //       System.out.println(" ............. False : Loguearse");
            System.out.println("  -- Usuario : " + usuario.getUsuario());
            return false;
        } else {
            //     System.out.println(" ............. True : Continua Logueado : ");
            return true;
        }
        //    return user != null ? true : false;
    }

    public void reroute() throws IOException {
        System.out.println(" ---- reroute() : ");
        FacesContext.getCurrentInstance().getExternalContext().redirect("logon.xhtml");
    }

    public String estalogueado() throws IOException {
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        System.out.println("req : " + req);
        HttpServletResponse resp = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        System.out.println(" resp : " + resp);
        HttpSession session = req.getSession(true);
        System.out.println(" Session : " + session);
        String pageRequested = req.getRequestURL().toString();
        System.out.println(" pageRequested : " + pageRequested);
        System.out.println(" -- pageRequest : " + pageRequested);
        String page = null;
        //     if (session.getAttribute(pageRequested) == null && !pageRequested.contains("logon.xhtml")) {
        if (session.getAttribute(pageRequested) == null) {
            System.out.println(" session.getAttribute(pageRequested)= Null : " + session.getAttribute(pageRequested));
            System.out.println(" 1 ");
            resp.sendRedirect("logon.xhtml");
            System.out.println(" 2 ");
            page = "logon?faces-redirect=true";
            System.out.println(" 3 ");
//----------------------------------------------  Código que cierra sesiones de usuario.
            FacesContext context = FacesContext.getCurrentInstance();
            ExternalContext externalContext = context.getExternalContext();
            //   Object session = externalContext.getSession(false);
            session = (HttpSession) externalContext.getSession(false);
            HttpSession httpSession = (HttpSession) session;
            httpSession.invalidate();
            System.out.println(" ------- cerrando session ");
            return page;
        }
        System.out.println(" session.getAttribute(pageRequested)= Null 2 : " + session.getAttribute(pageRequested));
        System.out.println(" ----- Usuario logueado " + session);
        return page;
    }

    public String logIn() {
        conseguirMAC();
        /*  Opcion 2
         try {
         System.out.println("Sistema Operativo     : " + System.getProperty("os.name"));
         System.out.println("Dirección IP          : " + InetAddress.getLocalHost().getHostAddress());
         System.out.println("Dirección Física (MAC): " + getMacAddress());
         } catch (Throwable t) {
         t.printStackTrace();
         }
         */

        /*  Opcion 1
         * Barre todas la IP de la red  
         Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
         while (en.hasMoreElements()) {
         NetworkInterface ni = en.nextElement();
         printParameter(ni);
         }
         */
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
        EntityManager em = factory.createEntityManager();
        Query q = em.createQuery("SELECT u FROM Usuario u WHERE u.usuario = :USER_NAME and u.clave = :USER_PASS ");
        q.setParameter("USER_NAME", usuario.getUsuario());
        q.setParameter("USER_PASS", usuario.getClave());
        Usuario usuario2;

        FacesMessage msg = null;
        boolean loggedIn = false;

        String page = null;
        String nauser = "";
        int tuser = 0;
        try {
            usuario2 = (Usuario) q.getSingleResult();
            this.usuario = usuario2;
            //     System.out.println(" ---------- Tipo de usuario : " + usuario2.getTipoUsuario().getIdTipoUsuario());
            tuser = usuario2.getTipoUsuario().getIdTipoUsuario();
            tipUserl = tuser;
            nauser = usuario2.getUsuario();
            //      FacesContext context4 = FacesContext.getCurrentInstance();
            //      context4.addMessage(null, new FacesMessage("Bienvenido al Sistema " , nauser));
            loggedIn = true;
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Bienvenido", nauser);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", nauser);


            if (tuser == 4) {
                page = "indexuser?faces-redirect=true";
            } else {
                page = "index?faces-redirect=true";
            }
            //                   return page;

        } catch (Exception e) {
            //      FacesContext context5 = FacesContext.getCurrentInstance();
            //      context5.addMessage(null, new FacesMessage("Error de Acceso ", "Verificar Usuario y Password ?"));
            loggedIn = false;
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, " Error en Acceso", "Credentiales Invalidas");
            FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);

            page = "logon?faces-redirect=true";
//            return page;
        }
        FacesContext.getCurrentInstance().addMessage(null, msg);
        RequestContext.getCurrentInstance().addCallbackParam("loggedIn", loggedIn);

        return page;
    }
//********************* Opcion 3 *****************

    public void conseguirMAC() {
        NetworkInterface a;
        String linea;
        try {
            a = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            byte[] mac = a.getHardwareAddress();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            FileWriter fwriter = new FileWriter("mac.dat");
            System.out.println(" --- ((( Validar  MAC ))) --- : " + sb.toString());
            fwriter.write("MAC: " + sb.toString());
            fwriter.close();
//            lmac.setText("SE ha registrado la MAC exitosamente.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//*************************** Opcion 2 ***********************************
    private final static String getMacAddress() throws IOException {
        String os = System.getProperty("os.name");
        try {
            if (os.startsWith("Windows")) {
                return windowsParseMacAddress(windowsRunIpConfigCommand());
            } else {
                throw new IOException("Sistema operativo desconocido: " + os);
            }
        } catch (ParseException ex) {
            ex.printStackTrace();
            throw new IOException(ex.getMessage());
        }
    }

    private final static String windowsParseMacAddress(String ipConfigResponse)
            throws ParseException {
        String localHost = null;
        try {
            localHost = InetAddress.getLocalHost().getHostAddress();
        } catch (java.net.UnknownHostException ex) {
            ex.printStackTrace();
            throw new ParseException(ex.getMessage(), 0);
        }

        StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
        String lastMacAddress = null;

        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken().trim();

            if (line.endsWith(localHost) && lastMacAddress != null) {
                return lastMacAddress;
            }

            int macAddressPosition = line.indexOf(":");
            if (macAddressPosition <= 0) {
                continue;
            }

            String macAddressCandidate = line.substring(macAddressPosition + 1)
                    .trim();
            if (windowsIsMacAddress(macAddressCandidate)) {
                lastMacAddress = macAddressCandidate;
                continue;
            }
        }

        ParseException ex = new ParseException(
                "Imposible obtener dirección MAC desde [" + ipConfigResponse
                + "]", 0);
        ex.printStackTrace();
        throw ex;
    }

    private final static boolean windowsIsMacAddress(String macAddressCandidate) {
        if (macAddressCandidate.length() != 17) {
            return false;
        }

        return true;
    }

    private final static String windowsRunIpConfigCommand() throws IOException {
        Process p = Runtime.getRuntime().exec("ipconfig /all");
        InputStream stdoutStream = new BufferedInputStream(p.getInputStream());

        StringBuffer buffer = new StringBuffer();
        for (;;) {
            int c = stdoutStream.read();
            if (c == -1) {
                break;
            }
            buffer.append((char) c);
        }
        String outputText = buffer.toString();

        stdoutStream.close();

        return outputText;
    }

//************************* Barre all IP de la Red*******************************************    
    public static void printParameter(NetworkInterface ni) throws SocketException {
        System.out.println("-----------------------------------------------------");
        System.out.println(" Nombre = " + ni.getName());
        System.out.println(" Nombre a mostrar= " + ni.getDisplayName());
        //  System.out.println(" Está activa = " + ni.isUp());
        //  System.out.println(" Soporte para multicast = " + ni.supportsMulticast());
        //   System.out.println(" Es loopback = " + ni.isLoopback());
        //   System.out.println(" Es virtual = " + ni.isVirtual());
        //   System.out.println(" Es punto a punto = " + ni.isPointToPoint());
        System.out.println(" Dirección MAC = " + ni.getHardwareAddress());
        System.out.println(" MTU = " + ni.getMTU());

        System.out.println("\n*** Lista de direcciones de interfaz:");
        List<InterfaceAddress> list = ni.getInterfaceAddresses();
        Iterator<InterfaceAddress> it = list.iterator();

        while (it.hasNext()) {
            InterfaceAddress ia = it.next();
            System.out.println("     Dirección = " + ia.getAddress());
            System.out.println("     Broadcast = " + ia.getBroadcast());
            System.out.println("     Longitud de prefijo de red = " + ia.getNetworkPrefixLength());
            System.out.println("");
        }
        System.out.println("=========================================================");
    }

//********************************************************************    
    public String logout() {
        // HttpSession session = Util.getSession();
        // session.invalidate();
        System.out.println(" Logout : login");
        return "login";
    }

//--------------------  Verifica Logueo ------------------------
    public String seekUser() {
        UsuarioController usuarioController = (UsuarioController) JsfUtil.getManagedBean("usuarioController");
        int idusu = usuarioController.getUsuario().getIdUsuario();
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
        EntityManager em = factory.createEntityManager();
        Query q = em.createQuery("SELECT t FROM Trabajador t join t.usuario u  WHERE u.idUsuario = :codtra "); // jalar id de otra tabla
        q.setParameter("codtra", idusu);
        Trabajador trabajador;
        String page = null;
        trabajador = (Trabajador) q.getSingleResult();
        this.trabajador = trabajador;   // alamacena data del Trabajador en consulta
        Trabajador traba = new Trabajador();
        String idLogueo = this.getTrabajador().getIdResponsable();  //        System.out.println(" ---- user logueado " + idLogueo);
        return idLogueo;
    }

    /*   public void userinactivo() throws IOException {
     // http://letconversion.com/tiempo-de-conversion/de-minutos/a-milisegundos  
     // 1 min   =     60000 milisegundo
     // 5 min   =   300000 milisegundo
     // 15 min  =   900000 milisegundo
     // 20 min  =  1200000 milisegundo
     String idLogueoViene = seekUser();
     if (idLogueoViene == null) {
     FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Error de Usuario ..!", "Usuario Inactivo expiro, Por Favor volver a ingresar al Sistema");
     RequestContext.getCurrentInstance().showMessageInDialog(message);
     reset();
     }
     }
     */
    /**
     * Flushes the session and redirects to the login.
     *
     */
    private void reset() throws IOException {
        // Flush();
        reroute();
    }

    /**
     * Destroys all session objects in the servlet.
     */
//    public final void Flush() {
//        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
//        request.getSession().invalidate();
//    }
    /**
     * Helps set to redirect toward the login page.
     */
    public void Reroute1() throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().redirect("logon.xhtml");
    }

//-------------------- Fin Verifica Logeo  ---------------------
    @FacesConverter(forClass = Usuario.class)
    public static class UsuarioControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UsuarioController controller = (UsuarioController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "usuarioController");
            return controller.getUsuario(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Usuario) {
                Usuario o = (Usuario) object;
                return getStringKey(o.getIdUsuario());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Usuario.class.getName());
            }
        }
    }
}
